package org.jeecg.modules.user.code.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xkcoding.http.util.StringUtil;
import org.jeecg.modules.system.allsmslog.entity.BikeSysSmsLog;
import org.jeecg.modules.system.allsmslog.service.BikeSysSmsLogService;
import org.jeecg.modules.user.code.entity.SmsCode;
import org.jeecg.modules.user.code.mapper.SmsCodeMapper;
import org.jeecg.modules.dto.SendSmsRes;
import org.jeecg.modules.user.member.entity.Member;
import org.jeecg.modules.user.member.mapper.MemberMapper;
import org.jeecg.modules.utils.BikeResult;
import org.jeecg.modules.utils.SMSDmeo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @author MrBird
 */
@Service
public class SmsCodeServiceImpl implements SmsCodeService {

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private SmsCodeMapper smsCodeMapper;
    @Autowired
    private BikeSysSmsLogService bikeSysSmsLogService;
    /**
     * 发送短信验证码
     * @return
     */
    @Override
    public BikeResult sendSmsCode(String phone, int type)  {
        if(StringUtil.isEmpty(phone) || phone.length() != 11) {
            return BikeResult.error("0","无效手机号！",null);
        }

        // 1:随机生成6位数的验证码
        String smsCode = "";
        for (int i = 0; i < 6; i++) {
            smsCode = smsCode + String.valueOf((int) Math.floor(Math.random() * 9 + 1));
        }

        // 3: 判断短信验证码类型(1:注册；2:忘记密码；3：修改密码；4：登录；5：微信绑定手机号)
        int expiredtime = 0;
        if(type == 1) {
            // 用户注册
            expiredtime = 10 * 60;

            // 判断该用户是否已经注册过--根据手机号查user
            QueryWrapper qw = new QueryWrapper();
            qw.eq("phone",phone);
            qw.ne("status","4");
            Member  member = memberMapper.selectOne(qw);
            if(member != null){
                return BikeResult.error("0","该用户已注册,请直接登陆！",null);
            }
        } else if(type == 2) {
            // 忘记密码
            expiredtime = 10 * 60;
        } else if(type == 3) {
            // 修改密码
            expiredtime = 10 * 60;
        } else if(type == 4) {
            // 登录
            expiredtime = 10 * 60;
            // 判断该用户是否已经注册过--根据手机号查user
            QueryWrapper qw = new QueryWrapper();
            qw.eq("phone",phone);
            qw.ne("status","4");
            Member  member = memberMapper.selectOne(qw);
            if(member == null){
                return BikeResult.error("0","账号未注册，请先注册账号！",null);
            }
        } else if(type == 5) {
            // 换绑手机号
            expiredtime = 10 * 60;
            QueryWrapper qw = new QueryWrapper();
            qw.eq("phone",phone);
            qw.ne("status","4");
            Member  member = memberMapper.selectOne(qw);
            if(member != null){
                return BikeResult.error("0","账号已存在！",null);
            }
        } else {
            return BikeResult.error("0","短信类型不支持！",null);
        }

        //发送短信验证码
        String result = SMSDmeo.send(phone, smsCode);
        Map resultMap= JSON.parseObject(result, Map.class);
        String resultCode= resultMap.get("status").toString();

        if(resultCode.equals("0")){
            String msg = "验证码" + smsCode + "，用于注册/登录，10分钟内有效。验证码提供给他人可能导致账号被盗，请勿泄漏，谨防被骗。";
            BikeSysSmsLog bikeSysSmsLog = new BikeSysSmsLog();
            bikeSysSmsLog.setType(type+"");
            bikeSysSmsLog.setMobile(phone);
            bikeSysSmsLog.setCreateBy("系统");
            bikeSysSmsLog.setContent(msg);
            bikeSysSmsLogService.add(bikeSysSmsLog);

            // 保存验证码时，查看表中是否已存在该手机号信息
            QueryWrapper smWrapper = new QueryWrapper();
            smWrapper.eq("mobile",phone);
            smWrapper.eq("type",type);
            SmsCode sms= smsCodeMapper.selectOne(smWrapper);
            if(sms != null){
                sms.setSmsCode(smsCode);
                sms.setRequestTime(new Date());
                sms.setType(String.valueOf(type));
                smsCodeMapper.updateById(sms);
            } else {
                sms = new SmsCode();
                sms.setMobile(phone);
                sms.setType(String.valueOf(type));
                sms.setSmsCode(smsCode);
                sms.setExpiredTime(expiredtime);
                sms.setRequestTime(new Date());
                smsCodeMapper.insert(sms);
            }
        } else {
            return BikeResult.error("0","发送验证码失败！",null);
        }

        SendSmsRes sendSmsRes = new SendSmsRes();
        // 支持前端直接赋值，客户要求必须手填
        // sendSmsRes.setSmscode(smsCode);
        sendSmsRes.setExpiredtime(expiredtime);
        return BikeResult.ok("1","验证码发送成功！",sendSmsRes);
    }

    /**
     * 校验短信验证码
     * @return
     */
    @Override
    public BikeResult checkSmsCode(SmsCode smsCode)  {
        //1根据手机号、类型、验证码去数据库查询该记录是否存在
        QueryWrapper smWrapper = new QueryWrapper();
        smWrapper.eq("mobile",smsCode.getMobile());
        smWrapper.eq("type",smsCode.getType());
        smWrapper.eq("sms_code",smsCode.getSmsCode());
        // 获取数据库验证码信息，验证码输入是否正确
        SmsCode sms = smsCodeMapper.selectOne(smWrapper);

        // 2：不存在，直接报验证码不正确
        if(sms != null) {
            // 3：存在此时判断验证码是否超时
            Date presentTime = new Date();
            Date requestTime = sms.getRequestTime();
            long time = presentTime.getTime() - requestTime.getTime();
            // 类型转换 1000,是一分钟，10000是十分钟
            int timeInt = new Long(time/(1000)).intValue();
            if (timeInt > sms.getExpiredTime()) {
                 return BikeResult.error("0","验证码已过期！",null);
            } else {
                return BikeResult.ok("200","验证码校验成功",true);
            }
        } else {
            return BikeResult.error("0","验证码不正确！",null);
        }
    }
}
